# txt文件操作
#1 案例1
def my_write():
    # 打开（创建）文件
    file = open('./a.txt', 'w', encoding='utf-8') # ./代表当前目录，../上一级目录
    # 写入内容
    file.write('伟大的中国梦')
    # 关闭文件
    file.close

def my_read():
    file = open('a.txt', 'r', encoding='utf-8')
    # 读取文件
    str1 = file.read()
    print(type(str1), str1)
    file.close
# 主程序运行
if __name__ == '__main__':
    my_write()
    my_read()

#2 写入操作
def my_write2(str2):
    file = open('b.txt', 'a', encoding='utf-8')
    file.write(str2)
    file.write('\n')
    file.close()

if __name__ == '__main__':
    my_write2('伟大的中国梦')
    my_write2('北京欢迎你')

#
def my_write_list(file, lst):
    f = open(file, 'a', encoding='utf-8')
    f.writelines(lst)
    f.close()

if __name__ == '__main__':
    lst = ['姓名\t', '年龄\t', '成绩\n',
           '张三\t', '30\t', '98\n',
    ]
    my_write_list('c.txt', lst)

#3 读取操作
def my_read2(filename):
    file = open(filename, 'w+', encoding='utf-8')
    file.write('你好啊')
    # seek修改文件的指针位置
    file.seek(0)
    #str2 = file.read()      # 读取全部
    #str2 = file.read(2)     # 读取两个字符
    #str2 = file.readline()  # 读取一行数据
    str2 = file.readline(2)  # 读取一行中的两个字符
    print(type(str2), str2)

    file.seek(3)        # utf-8，一个中文占3个字节
    str2 = file.read()
    print(type(str2), str2) # 好啊

    file.seek(0)
    lst2 = file.readlines()  # 读取所有，一行为列表的一个元素
    print(type(lst2), lst2)
    file.close()

if __name__ == '__main__':
    my_read2('d.txt')

#4 文件的复制-边读边写
def copy(src, new_path):
    file1 = open(src, 'r', encoding='utf-8')
    file2 = open(new_path, 'w', encoding='utf-8')
    str = file1.read()
    file2.write(str)
    # 文件关闭（先打开的后关，后打开的先关）
    file2.close()
    file1.close()

if __name__ == '__main__':
    copy('d.txt', 'e.txt')

#5 with语句
#
def write_fun():
    with open('aa.txt', 'w', encoding='utf-8') as file:
        file.write('2022北京东奥会欢迎你')

def read_fun():
    with open('aa.txt', 'r', encoding='utf-8') as file:
        print(file.read())

def copy_fun(src_file, target_file):
    with open(src_file, 'r', encoding='utf-8') as file1:
        with open(target_file, 'w', encoding='utf-8') as file2:
            str1 = file1.read()
            file2.write(str1)

if __name__ == '__main__':
    write_fun()
    read_fun()
    copy_fun('./aa.txt', 'bb.txt')